package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.PeachBlossom;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class PeachblossomApiImpl implements PeachblossomApi {

    @Autowired
    private MongoTemplate mongoTemplate;
/*
桃花传音--发送语音
 */
    @Override
    public Boolean save(PeachBlossom peachBlossom) {
        peachBlossom.setId(ObjectId.get());
        peachBlossom.setCreated(System.currentTimeMillis());
        PeachBlossom save = mongoTemplate.save(peachBlossom);
        if (save == null) {
            return false;
        }
        return true;
    }


    /*
    桃花传音--接受语音
     */
    @Override
    public PeachBlossom findVoice(Long userId, String gender) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").ne(userId).and("gender").ne(gender))
                .with(Sort.by(Sort.Order.desc("created")));
        List<PeachBlossom> peachBlossomList = mongoTemplate.find(query, PeachBlossom.class);
        //随机的index
        long total = mongoTemplate.count(query, PeachBlossom.class);
        int index = RandomUtils.nextInt(0,(int)total-1);
        PeachBlossom peachBlossom = peachBlossomList.get(index);
        return peachBlossom;
    }
}
